package com.hgw.Demo06_Singleton.test;

import java.util.ArrayList;
import java.util.List;

/**
 * Data time:2021/12/11 14:40
 * StudentID:2019112118
 * Author:hgw
 * Description:
 */
public class test11708 {
    public static void main(String[] args) {
        DatabaseCP database1,database2,database3;
        database1 = DatabaseCP.getInstance();
        database2 = DatabaseCP.getInstance();
        database3 = DatabaseCP.getInstance();

        // 给不同数据库连接对象
        database1.addDatabase("连接mysql");
        database2.addDatabase("连接oracle");
        database2.addDatabase("连接sqlite");

        database1.getDatabaseList().forEach(data -> System.out.println(data));
    }
}

class DatabaseCP {
    // 1、本类内部构建对象实例
    private static DatabaseCP instance;

    private List databaseList = null;

    // 2、构造器私有化
    private DatabaseCP(){
        databaseList = new ArrayList();
    }

    // 3、提供一个静态的公有方法，加入同步处理的代码 synchronized，解决线程安全问题
    public static synchronized DatabaseCP getInstance() {
        if (instance == null ){
            instance = new DatabaseCP();
        }
        return instance;
    }

    public void addDatabase(String database) {
        databaseList.add(database);
    }

    public void removeDatabase(String database) {
        databaseList.remove(database);
    }

    public List getDatabaseList() {
        return databaseList;
    }
}
